<!DOCTYPE html>
<title>Media Controls: overflow menu pointer selection</title>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="../media-controls.js"></script>
<body>
</body>
<script>

function moveMouseTo(x, y) {
  return new Promise((resolve, reject) => {
    chrome.gpuBenchmarking.pointerActionSequence([{
      source: 'mouse',
      actions: [ { name: 'pointerMove', x: x, y: y } ],
    }], resolve);
  });
}

async function testMouseMoveInsideElement(root, element) {
  const box = element.getBoundingClientRect();
  const y = box.top + (box.height / 2);

  // Move the mouse from the left (middle-height) of the element to the right.
  // The element is expected to stay focused while this is happening.
  for (let x = box.left + 10; x < box.right; x += 10) {
    await moveMouseTo(x, y);
    assert_equals(root.activeElement, element);
  }
}

async function testMouseEventForElements(root, elements) {
  for (let i = 0; i < elements.length; i++)
    await testMouseMoveInsideElement(root, elements[i]);
}

async_test(t => {
  assert_true('internals' in window);
  assert_true('eventSender' in window);
  assert_true('chrome' in window);

  const video = document.createElement('video');
  video.controls = true;
  video.src = '../content/test.ogv';
  internals.mediaPlayerRemoteRouteAvailabilityChanged(video, true);

  [ '../track/captions-webvtt/captions-fast.vtt',
    '../track/captions-webvtt/captions-rtl.vtt' ].forEach(source => {
    const track = document.createElement('track');
    track.src = source;
    track.kind = 'captions';
    video.appendChild(track);
  });

  assert_equals(video.textTracks.length, 2);

  document.body.appendChild(video);
  enableTestMode(video);

  video.addEventListener('loadedmetadata', t.step_func(() => {
    assert_true(isVisible(overflowButton(video)));
    singleTapOnControl(overflowButton(video), t.step_func(() => {
      const menu = overflowMenu(video);
      assert_true(isVisible(menu));

      const root = internals.shadowRoot(video);
      const elements = [ menu.lastElementChild,
                         menu.lastElementChild.previousSibling ];

      testMouseEventForElements(root, elements).then(t.step_func(() => {
        // Move focus to bottom element via keyboard then move back to top one
        // via mouse.
        elements.forEach(_ => eventSender.keyDown('ArrowDown'));
        assert_equals(root.activeElement, menu.lastElementChild);

        const target = elements[0];
        const coord = elementCoordinates(target);
        chrome.gpuBenchmarking.pointerActionSequence([{
          source: 'mouse',
          actions: [ { name: 'pointerMove', x: coord[0], y: coord[1] } ],
        }], t.step_func_done(() => {
          assert_equals(root.activeElement, target);
        }));
      }));
    }));
  }), { once: true });
});
</script>
